<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Manage Your Tasks</title>
<style>
body {
	font: normal 12px/2 Consolas, arial;
}

ul {
	list-style: decimal;
}
</style>
</head>
<body>
<h1>Manage Your Tasks</h1>
<h2>Add a task</h2>
<div>
<form>
<input type="text" id="tasktext" name="tasktext" required="required">
<button type="button" id="btn_addtask">Add</button>
</form>
</div>

<h2>My tasks</h2>
<ul id="mytasks">
</ul>

<script type="text/javascript">

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
};

(function(){
	
	if (typeof openDatabase == 'undefined') {
		alert('the broser is not support web sql database');
		return;
	}

	var db = openDatabase('tasks', '1.0', 'db of my tasks', 2*1024*1024);
	db.transaction(function(tx){
		tx.executeSql('create table if not exists tasks (date TEXT, text TEXT)', []);
	});
	
	function addTask(){
		var oTasktext = document.querySelector('#tasktext');
		var tasktext = oTasktext.value;
		if (tasktext == '') {
			alert('input your task.');
			oTasktext.focus();
			return;
		}
		
		var date = new Date().getDate();
		
		db.transaction(function(tx){
			tx.executeSql('insert into tasks values(?,?)',[date, tasktext], function(tx,rs){
				console.log(rs);
			}, function(tx, err){
				console.log(err);
			});
		});
		
		oTasktext.value = '';
	}
	function showMyTasks(){
		var ul = document.querySelector('#mytasks');
		ul.innerHTML = '';
		db.transaction(function(tx){
			tx.executeSql('select * from tasks order by date desc', [], function(tx, rs){
				for(var i = 0, l = rs.rows.length; i < l; i += 1){
					var li = document.createElement('li');
					li.innerHTML = rs.rows.item(i).text;
					ul.appendChild(li);
				}
			});
		});
	}
	
	function bindEvent(){
		document.querySelector('#btn_addtask').addEventListener('click', function(e) {
			addTask();
			showMyTasks();
		}, false);
		
		document.querySelector('form').onsubmit = function(){
			addTask();
			showMyTasks();
			return false
		};
	}
	
	window.onload = function() {
		showMyTasks();
		bindEvent();
	};
})();
</script>

</body>
</html>